<template>
  <div class="echarts-box" v-show="store.curEditChartType !== ''">
    <div id="myEcharts" style="height: 60vh; width: 50vw">
    </div>
  </div>
  <el-empty description="暂无图表" v-if="store.curEditChartType === ''" />
</template>

<script setup lang="ts">
import _ from 'lodash'
import { watch, onMounted, reactive, ref, nextTick, onBeforeUnmount } from 'vue'
import { EChartsOption, init } from 'echarts'

import { EChartsConfigForm } from '../../types/EChartsConfigForm'
import { useDebounce } from '../../hooks/useDebounce'
import { chartStore } from '../../store/index'

const store: any = chartStore()

let debounce = useDebounce
let form: EChartsConfigForm = store.form
let chart: any = null

onMounted(() => {
  initChart()
  drawChart()
})

onBeforeUnmount(() => {
  // 内存回收
  chart = null
})

// 更新源代码
const updateOptionCode = (value: EChartsOption) => {
  const originCode = JSON.stringify(value, null, 4)
  store.setOriginCode(originCode)
}

// 图表实例初始化
function initChart() {
  const chartEle: HTMLElement = document.getElementById(
    'myEcharts'
  ) as HTMLElement
  chart = init(chartEle)
}

// 绘制图表
function drawChart() {
  const commonConfig = {
    legend: {},
    tooltip: {},
    series: [],
  }

  // 刷新图表
  const option: EChartsOption = _.merge(commonConfig, form)
  const NOT_MERGE = true
  option && chart.setOption(option, NOT_MERGE)

  // 更新源代码
  updateOptionCode(option)

  // 自适应大小
  window.onresize = function () {
    chart.resize()
  }
}

watch(
  form,
  () => {
    debounce(() => {
      drawChart()
    }, 300)
  },
  { deep: true }
)
</script>

<style lang="less" scoped>
.echarts-box {
  background-color: #f8f8f8;
  border-radius: 10px;
  padding: 20px;
}
</style>
